package com.lanjiu.lib.business.option;

import com.lanjiu.lib.utils.log.Logger;
import com.lanjiu.lib.utils.th.Threader;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/2/18 16:51
 */
public class ShutdownTimer {

    private static final int IDLE_TIME = 60 * 1000; // 文件channel最长闲置时间包括碎片传输时间(单位:毫秒)

    private long mStartTimeMillis;
    private ExecutorService mExecutorService;
    private boolean isRunning;

    public ShutdownTimer(OnTimeoutListener listener) {
        if (mExecutorService != null) {
            if (!mExecutorService.isShutdown())
                mExecutorService.shutdownNow();
            mExecutorService = null;
        }
        mExecutorService = Executors.newSingleThreadExecutor();
        this.mOnTimeoutListener = listener;
        isRunning = false;
    }

    public void start() {
        isRunning = true;
        Logger.print("ShutdownTimer", "start");
        mStartTimeMillis = System.currentTimeMillis();
        mExecutorService.execute(new ShutdownTask());
    }

    public void update() {
        Logger.print("ShutdownTimer", "update");
        mStartTimeMillis = System.currentTimeMillis();
    }

    private OnTimeoutListener mOnTimeoutListener;

    public class ShutdownTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                if (abs(System.currentTimeMillis() - mStartTimeMillis) >= IDLE_TIME) {
                    isRunning = false;
                    break;
                }
                Threader.sleep(16);
            }
            Logger.print("ShutdownTimer", "timeout");
            if (mOnTimeoutListener != null)
                mOnTimeoutListener.onTimeout();
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public interface OnTimeoutListener {
        void onTimeout();
    }

    public static long abs(long flag) {
        if (flag < 0)
            return -flag;
        return flag;
    }
}
